package com.common.servlet.abstracts;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.common.model.abstracts.AbstractRequest;
import com.common.security.abstracts.AbstractException;
import com.common.security.errors.ParserError;
import com.common.security.exceptions.HTTPException;
import com.common.security.exceptions.ParserException;

/**
 * The AbstractParserServer is an AbstractServlet that has it's exception method
 * implemented to handle ParserExceptions.
 * 
 * @author Ady
 *
 */
public abstract class AbstractParserServlet extends AbstractServlet {
	private static final long serialVersionUID = 1L;

	@Override
	public AbstractRequest parseRequest(HttpServletRequest request) throws ParserException, HTTPException, IOException {
		return parser().parseRequest(request.getInputStream());
	}
	
	@Override
	public void exception(AbstractException exception, HttpServletResponse response) {
		switch (exception.getCode()) {
			case ParserException.STREAM_ERROR: {
				error(new ParserError(ParserError.STREAM_ERROR), response);
				break;
			}
			case ParserException.MULTIPLE_ACTIONS_PROVIDED: {
				error(new ParserError(ParserError.MULTIPLE_ACTIONS_PROVIDED), response);
				break;
			}
			case ParserException.NO_ACTION_PROVIDED: {
				error(new ParserError(ParserError.NO_ACTION_PROVIDED), response);
				break;
			}
			case ParserException.MULTIPLE_CONTENTS_PROVIDED: {
				error(new ParserError(ParserError.MULTIPLE_CONTENTS_PROVIDED), response);
				break;
			}
			case ParserException.NO_CONTENT_PROVIDED: {
				error(new ParserError(ParserError.NO_CONTENT_PROVIDED), response);
				break;
			}
			case ParserException.CONTENT_BAD_FORMAT: {
				error(new ParserError(ParserError.CONTENT_BAD_FORMAT), response);
				break;
			}
			case ParserException.RESPONSE_MATCH_ERROR: {
				error(new ParserError(ParserError.RESPONSE_MATCH_ERROR), response);
				break;
			}
			case HTTPException.ACTION_NOT_AVAILABLE: {
				error(new ParserError(ParserError.ACTION_NOT_AVAILABLE), response);
				break;
			}
		}
	}
}
